﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Collections;
using MensUnoShop.Models;
using MensUnoShop.Filters;
using MensUnoShop.Models.ViewModels;
using System.Net.Mail;
using SenerPro;
using System.Xml.Linq;

namespace MensUnoShop.Controllers
{
    public class MemberController : Controller
    {
        //
        // GET: /Member/
        private Member _member;
        private List<Tag> _toptaglist, _navlist, _leftlist;
        private string _title;
        private List<MemberFavorite> _mflist;
        private List<UNews> _newslist;
        private XElement _hotkeylist;

        public MemberController() 
        {
            _member = MemberFactory.GetMember();
            _toptaglist = TagFactory.GetTopTagList();
            _newslist = NewsFactory.GetNewsList();
            _hotkeylist = KeyWordFactory.GetHotKeyList();
        }

        public ActionResult join_step1()
        {
            if (_member == null)
            {
                _toptaglist = TagFactory.GetTopTagList();
                _leftlist = TagFactory.GetLeftTagList(1);
                RegionViewModel iv = new RegionViewModel { MEMBER = _member, TITLE = _title, TOPLIST = _toptaglist, LEFTTAG = _leftlist, NEWS = _newslist, HOTKEYLIST = _hotkeylist };
                return View(iv);
            }
            else
                return Redirect("/");
        }

        public ActionResult join_step2()
        {
            if (_member == null)
            {
                _toptaglist = TagFactory.GetTopTagList();
                _leftlist = TagFactory.GetLeftTagList(1);
                RegionViewModel iv = new RegionViewModel { MEMBER = _member, TITLE = _title, TOPLIST = _toptaglist, LEFTTAG = _leftlist, NEWS = _newslist, HOTKEYLIST = _hotkeylist };
                return View(iv);
            }
            else
                return Redirect("/");
        }

        [HttpPost]
        public ActionResult join_step2(FormCollection fm)
        {
            if (_member == null)
            {
                foreach (var s in fm.AllKeys)
                {
                    fm[s].Replace("'", "");
                }
                string _email = fm["email"];
                string _password = fm["password"];
                string _confirm = fm["confirm"];
                string _firstname = fm["firstname"];
                string _lastname = fm["lastname"];
                string _telh = fm["telh_pre"] + "-" + fm["telh"];
                string _telo = fm["telo_pre"] + "-" + fm["telo"];
                string _mobile = fm["mobile"];
                bool _ismarried = bool.Parse(fm["ismarried"]);
                bool _sex = bool.Parse(fm["sex"]);
                //string _birth = DateTime.Parse(fm["year"] + "/" + fm["month"] + "/" + fm["days"]).ToShortDateString();
                string _birth = fm["birthday"];
                string _edu = fm["degree"];
                string _job = fm["job"];
                string _income = fm["money"];
                string _country = fm["country"];
                string _zip = fm["zip"];
                string _city = fm["city"];
                string _area = fm["area"];
                string _address = fm["address"];
                bool _isedm = bool.Parse(fm["isedm"]);
                TempData["email"] = _email;
                //TempData["_password"] = _password;
                //TempData["_confirm"] = _confirm;
                TempData["firstname"] = _firstname;
                TempData["lastname"] = _lastname;
                TempData["telh_pre"] = fm["telh_pre"];
                TempData["telh"] = fm["telh"];
                TempData["telo_pre"] = fm["telo_pre"];
                TempData["telo"] = fm["telo"];
                TempData["mobile"] = _mobile;
                TempData["ismarried"] = _ismarried;
                TempData["sex"] = _sex;
                TempData["birthday"] = _birth;
                TempData["degree"] = _edu;
                TempData["job"] = _job;
                TempData["money"] = _income;
                TempData["country"] = _country;
                TempData["zip"] = _zip;
                TempData["city"] = _city;
                TempData["area"] = _area;
                TempData["address"] = _address;
                if (!string.IsNullOrEmpty(_email) && !string.IsNullOrEmpty(_password) && !string.IsNullOrEmpty(_confirm) && _password == _confirm)
                {
                    string code = string.Empty;
                    if (MemberFactory.AddNormalMember(_email, _password, _firstname, _lastname, _telh, _telo, _mobile, _ismarried, _sex, _birth, _edu, _job, _income, _country, _zip, _city, _area, _address, _isedm))
                    {
                        TempData.Clear();
                        return View("ErRedirect", new ErrorViewModel() { ALERT = "請至信箱收取認證通知信", URI = "/" });
                    }
                    else
                        return View("ErRedirect", new ErrorViewModel() { ALERT = "帳號已存在", URI = Request.UrlReferrer.ToString() });
                }
                return View("ErRedirect", new ErrorViewModel() { ALERT = "輸入資料有誤", URI = Request.UrlReferrer.ToString() });
            }
            else
                return Redirect("/");
        }

        public ActionResult Open(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                string msg = string.Empty;
                MemberFactory.StartNewMember(id, ref msg);
                return View("ErRedirect", new ErrorViewModel() { ALERT = msg, URI = "/" });
            }
            else
            {
                return View("ErRedirect", new ErrorViewModel() { ALERT = "資料驗證有誤", URI = "/" });

            }
        }

        [HttpPost]
        public ActionResult Login(string email, string pwd, string returnUrl)
        {
            string err = string.Empty;
            if(MemberFactory.CheckMemberLogin(email,pwd, ref err))
                return Redirect(returnUrl);
            else
                return View("ErRedirect", new ErrorViewModel() { ALERT = err, URI = "/" });
        }

        [MemberCheckFilter]
        public ActionResult Logout()
        {
            MemberFactory.MemberFree();
            ShoppingCart sc = new ShoppingCart();
            sc.FreeCookie();
            return Redirect("/");
        }


        public string Mail()
        {
            string mailcontent = System.IO.File.ReadAllText(Server.MapPath(Config.Latter_Join)).Replace("[fname]", "Sener").Replace("[lname]", "Huang").Replace("[mguid]", "12345");
            string error;
            //SenerPro.Tools.SendMail("加入會員確認信", mailcontent, "senerhuang@gmail.com", "Sener,Huang", Config.SMTPServer, new System.Net.Mail.MailAddress("system@mensunoshop.com", "Men's Uno Shop"), out error);
            
           

            return "NO: ]";
        }

        [MemberCheckFilter]
        public ActionResult edit_member() 
        {
            _toptaglist = TagFactory.GetTopTagList();
            _leftlist = TagFactory.GetLeftTagList(1);
            _member.GetCoupon();

            if (_member != null)
            {
                ViewData["telh_pre"] = "";
                ViewData["telh"] = "";
                ViewData["telo_pre"] = "";
                ViewData["telo"] = "";

                if (_member.TELH.Length > 0)
                {
                    ViewData["telh_pre"] = _member.TELH.Substring(0, _member.TELH.IndexOf('-'));
                    ViewData["telh"] = _member.TELH.Substring(_member.TELH.IndexOf('-') + 1, _member.TELH.Length - _member.TELH.IndexOf('-') - 1);
                }

                if (_member.TELO.Length > 0)
                {
                    ViewData["telo_pre"] = _member.TELO.Substring(0, _member.TELO.IndexOf('-'));
                    ViewData["telo"] = _member.TELO.Substring(_member.TELO.IndexOf('-') + 1, _member.TELO.Length - _member.TELO.IndexOf('-') - 1);
                }

                #region 學歷
                List<SelectListItem> degreeList = new List<SelectListItem>();
                degreeList.Add(new SelectListItem { Value = "0", Text = "請選擇" });
                degreeList.Add(new SelectListItem { Value = "高中(職)", Text = "高中以下Semior high under" });
                degreeList.Add(new SelectListItem { Value = "大學", Text = "大學University" });
                degreeList.Add(new SelectListItem { Value = "研究所", Text = "研究所M.D" });
                degreeList.Add(new SelectListItem { Value = "博士", Text = "博士Dr." });
                #endregion
                #region 職業
                List<SelectListItem> jobList = new List<SelectListItem>();
                jobList.Add(new SelectListItem { Value = "百貨業", Text = "百貨業Merchandise industry" });
                jobList.Add(new SelectListItem { Value = "文教業", Text = "文教業Education" });
                jobList.Add(new SelectListItem { Value = "大眾傳播業", Text = "大眾傳播業Media" });
                jobList.Add(new SelectListItem { Value = "休閒旅遊業", Text = "休閒旅遊業Tourism" });
                jobList.Add(new SelectListItem { Value = "服務業", Text = "服務業Service" });
                jobList.Add(new SelectListItem { Value = "高科技產業", Text = "高科技產業High-tech" });
                jobList.Add(new SelectListItem { Value = "運輸業", Text = "運輸業Transportation" });
                jobList.Add(new SelectListItem { Value = "工商業", Text = "工商業Commerce &amp; Industry" });
                jobList.Add(new SelectListItem { Value = "醫療保健", Text = "醫療保健" });
                jobList.Add(new SelectListItem { Value = "其它", Text = "其它Other" });
                #endregion
                #region 收入
                List<SelectListItem> incomeList = new List<SelectListItem>();
                incomeList.Add(new SelectListItem { Value = "30000", Text = "Under 30,000以下" });
                incomeList.Add(new SelectListItem { Value = "3~50,000", Text = "3~50,000" });
                incomeList.Add(new SelectListItem { Value = "5~80,000", Text = "5~80,000" });
                incomeList.Add(new SelectListItem { Value = "8~100,000", Text = "8~100,000" });
                incomeList.Add(new SelectListItem { Value = "100,000~150,000", Text = "100,000~150,000" });
                incomeList.Add(new SelectListItem { Value = "Above 200,000 以上", Text = "Above 200,000 以上" });
                #endregion
                #region 國籍
                string[] country = { "Australia", "Belgium", "Canada", "France", "Germany", "Italy", "Japan", "Korea", "Macao", "Malaysia", "Netherlands", "Singapore", "Spain", "Switzerland", "Taiwan", "Thailand", "UnitedKingdom", "UnitedStates", "Afghanistan", "Albania", "Algeria", "American", "Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "AntiguaandBarbuda", "Argentina", "Armenia", "Aruba", "Austria", "Azerbaidjan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "BosniaandHerzegovina", "Botswana", "BouvetIsland", "Brazil", "BritishIndianOceanT-tory", "Brunei", "Bulgaria", "BurkinaFaso", "Burundi", "Cambodia", "Cameroon", "CapeVerde", "CaymanIslands", "CentralAfricanRepublic", "Chad", "Chile", "China", "ChristmasIsland", "Cocos(Keeling)Islands", "Colombia", "Comoros", "CookIslands", "CostaRica", "CoteD'Ivoire", "Croatia", "Cuba", "Cyprus", "CzechRepublic", "Denmark", "Djibouti", "Dominica", "DominicanRepublic", "EastTimor", "Ecuador", "Egypt", "ElSalvador", "EquatorialGuinea", "Eritrea", "Estonia", "Ethiopia", "FalklandIslands", "FaroeIslands", "Fiji", "Finland", "FrenchGuiana", "FrenchPolynesia", "Gabon", "Gambia", "Georgia", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "HeardIs.andMcDonaldIs.", "HolySee(VaticanCityState)", "Honduras", "HongKong", "Hungary", "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Jamaica", "Jordan", "Kazakstan", "Kenya", "Kiribati", "North", "South", "Kuwait", "Kyrgyzstan", "Lao", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", "Macedonia", "Madagascar", "Malawi", "Maldives", "MaliMalta", "MarshallIslands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "NetherlandsAntilles", "NewCaledonia", "NewZealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk", "NorthernMarianaIslands", "Norway", "Oman", "Pakistan", "Palau", "PalestinianState(Proposed)", "Panama", "PapuaNewGuinea", "Paraguay", "Peru", "Philippines", "PitcairnIsland", "PolandPortugal", "Qatar", "RepublicofCongo", "Reunion", "Romania", "RussianFederation", "Rwanda", "S.GeorgiaandS.SandwichIs.", "SaintHelena", "SaintKittsandNevis", "SaintLucia", "SaintPierreandMiquelon", "Samoa", "SanMarino", "SaoTomeandPrincipe", "SaudiArabia", "Senegal", "SerbiaandMontenegro", "Seychelles", "SierraLeone", "Singapore", "Slovakia", "Slovenia", "SolomonIslands", "Somalia", "SouthAfrica", "SriLanka", "StVincentandtheGrenadines", "Sudan", "Suriname", "Svalbard", "Swaziland", "Sweden", "Syria", "Tajikistan", "Tanzania", "Thailand", "Togo", "Tokelau", "Tonga", "TrinidadandTobago", "TromelinIsland", "Tunisia", "Turkey", "Turkmenistan", "TurksandCaicosIslands", "Tuvalu", "Uganda", "Ukraine", "UnitedArabEmirates", "UruguayUSMinorOutlyingIslands", "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "VirginIslands(BritishVirginIslands)", "UnitedStatesWallisandFutunaIslands", "WesternSahara", "Yemen", "Yugoslavia", "Zaire", "Zambia", "Zimbabwe", "others" };
                List<SelectListItem> countryList = new List<SelectListItem>();
                for (int i = 0; i < country.Length; i++)
                {
                    countryList.Add(new SelectListItem { Text = country[i], Value = country[i] });
                }
                #endregion

                ViewData["degreeList"] = new SelectList(degreeList, "Value", "Text", _member.EDU);
                ViewData["jobList"] = new SelectList(jobList, "Value", "Text", _member.JOB);
                ViewData["incomeList"] = new SelectList(incomeList, "Value", "Text", _member.INCOME);
                ViewData["countryList"] = new SelectList(countryList, "Value", "Text", _member.COUNTRY);

                RegionViewModel iv = new RegionViewModel { MEMBER = _member, TITLE = _title, TOPLIST = _toptaglist, LEFTTAG = _leftlist, NEWS = _newslist, HOTKEYLIST = _hotkeylist };
                return View(iv);
            }
            else
            {
                return View("ErRedirect", new ErrorViewModel() { ALERT = "您尚未登入!", URI = "/" });
            }            
        }

        [HttpPost]
        public ActionResult edit_member(FormCollection fm)
        {
            #region
            foreach (var s in fm.AllKeys)
            {
                fm[s].Replace("'", "");
            }
            string _email = fm["email"];
            string _password = fm["password"];
            string _confirm = fm["confirm"];
            string _firstname = fm["firstname"];
            string _lastname = fm["lastname"];
            string _telh = fm["telh_pre"] + "-" + fm["telh"];
            string _telo = fm["telo_pre"] + "-" + fm["telo"];
            string _mobile = fm["mobile"];
            bool _ismarried = bool.Parse(fm["ismarried"]);
            bool _sex = bool.Parse(fm["sex"]);            
            string _birth = fm["birthday"];
            string _edu = fm["degree"];
            string _job = fm["job"];
            string _income = fm["income"];
            string _country = fm["country"];
            string _zip = fm["zip"];
            string _city = fm["city"];
            string _area = fm["area"];
            string _address = fm["address"];
            bool _isedm = bool.Parse(fm["isedm"]);
            # endregion


            if (_member != null)
            {
                #region
                _member.EMAIL = _email;
                _member.FIRSTNAME = _firstname;
                _member.LASTNAME = _lastname;
                _member.TELH = _telh;
                _member.TELO = _telo;
                _member.MOBILE = _mobile;
                _member.ISMARRIED = _ismarried;
                _member.SEX = _sex;
                _member.BIRTH = _birth;
                _member.EDU = _edu;
                _member.JOB = _job;
                _member.INCOME = _income;
                _member.COUNTRY = _country;
                _member.ZIP = _zip;
                _member.CITY = _city;
                _member.AREA = _area;
                _member.ADDRESS = _address;
                _member.ISEDM = _isedm;
                #endregion

                if (MemberFactory.UptMemberData(_member))
                {
                    _member.UptCookie();
                    if (!string.IsNullOrEmpty(_password) && !string.IsNullOrEmpty(_confirm) && _password == _confirm)
                    {
                        if (MemberFactory.UptMember(_member.MGUID, _member.EMAIL, _password, true))
                        {
                            return View("ErRedirect", new ErrorViewModel() { ALERT = "會員資料與密碼修改成功", URI = "/member/edit_member" });
                        }
                        else
                        {
                            return View("ErRedirect", new ErrorViewModel() { ALERT = "會員資料修改成功，密碼修改失敗!", URI = Request.UrlReferrer.ToString() });
                        }
                    }
                    else
                    {
                        return View("ErRedirect", new ErrorViewModel() { ALERT = "會員資料修改成功", URI = "/member/edit_member" });
                    }
                }
                else
                    return View("ErRedirect", new ErrorViewModel() { ALERT = "會員資料修改失敗", URI = Request.UrlReferrer.ToString() });
            }
            else
            {
                return View("ErRedirect", new ErrorViewModel() { ALERT = "您尚未登入!", URI = "/" });
            }


        }

        [HttpGet]
        public ActionResult forget_password()
        {
            _toptaglist = TagFactory.GetTopTagList();
            _leftlist = TagFactory.GetLeftTagList(1);
            if (_member != null)
            {
                return View("ErRedirect", new ErrorViewModel() { ALERT = "", URI = "/edit_member" });
            }
            else
            {
                RegionViewModel iv = new RegionViewModel { MEMBER = _member, TITLE = _title, TOPLIST = _toptaglist, LEFTTAG = _leftlist, NEWS = _newslist, HOTKEYLIST=_hotkeylist };
                return View(iv);
            }            
        }

        [HttpPost]
        public ActionResult forget_password(FormCollection fm)
        {
            string email = fm["email"];
            if (MemberFactory.NotifyPwd(email))
            {
                return View("ErRedirect", new ErrorViewModel() { ALERT = "密碼已寄信至您的E-Mail", URI = "/" });
            }
            else
            {
                return View("ErRedirect", new ErrorViewModel() { ALERT = "無此會員!", URI = "/" });
            }
        }

        public ActionResult my_favorite()
        {
            if (_member != null)
            {
                _mflist = MemberFactory.GetMemberFavorite(_member.MGUID);

                if (_mflist.Count == 0)
                    return View("ErRedirect", new ErrorViewModel() { ALERT = "目前沒有任何商品No items!", URI = "/" });
                else
                {

                    RegionViewModel iv = new RegionViewModel { MEMBER = _member, TITLE = _title, TOPLIST = _toptaglist, LEFTTAG = _leftlist, MEMBERFAVORITE = _mflist, NEWS = _newslist };
                    return View(iv);
                }
            }
            else
            {                
                return View("ErRedirect", new ErrorViewModel() { ALERT = "您未登入!", URI = "/" });
            }     
        }

        [HttpPost]
        public JsonResult del_my_favorite(Guid mfid)
        {
            if (MemberFactory.DelMemberFavorite(mfid))
            {
                return Json(new { code = "200", response = "" });
            }
            else
                return Json(new { code = "500", response = "" });
        }

        [HttpPost]
        public JsonResult add_my_favorite(Guid mguid, Guid mkguid, Guid productid, Guid specid)
        {
            if (mguid == Guid.Empty)
                return Json(new { code = "400", response = "請先登入" });
            else
            {
                if (MemberFactory.AddMemberFavorite(mguid, mkguid, productid, specid))
                {
                    return Json(new { code = "200", response = "" });
                }
                else
                    return Json(new { code = "500", response = "新增失敗" });
            }
        }

        [HttpPost]
        [MemberCheckFilter]
        public ActionResult addcoupon(string id)
        { 
            if(_member.SetCoupon(id))
                return View("ErRedirect", new ErrorViewModel() { ALERT = "優惠券登錄成功!", URI = Request.UrlReferrer.ToString() });
            else
                return View("ErRedirect", new ErrorViewModel() { ALERT = "您所輸入的序號錯誤，或該序號被登錄。\\n請您查明後再重新輸入或至電服務人員。\\n02-27316690 分機 501胡小姐。", URI = Request.UrlReferrer.ToString() });
        }

    }
}
